<template>
	<view>
		<view class="blank"></view>
		<view class="column" style="padding: 30rpx 35rpx;">
			<view class="" style="padding: 20rpx 0rpx;">
				兑换环保袋
			</view>
			<view class="row"
				style="width: 100%;padding: 20rpx 0rpx;border-bottom: solid 1rpx #cbcbcb;align-items: flex-end;justify-content: space-between;">
				<text style="font-size: 40rpx;">兑换价格:{{bagProduct.itemValue}}</text>
				<text style="font-size: 32rpx;color: #888888;">剩余{{userInfo.totalPoints}}云豆</text>
			</view>
			<text style="font-size: 24rpx;color: #888888;margin-top: 20rpx;">扫描设备兑换环保袋</text>
		</view>
		
		<view class="global-button " @click="scan" style="margin: 60rpx auto;">
			扫一扫
		</view>
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="warning" title="提示" :buttonArr="['取消','确定']" :content="content"
				@confirm="dialogConfirm" @close="dialogClose"></uni-popup-dialog>
		</uni-popup>
		<uni-popup ref="progress" type="center" :maskClick="false">
			<view class="column align-items-center" style="width: 100%;height: 100%;">
				<arprogress borderWidth="22" width="400" inactiveColor="#eee" activeColor="#3ED2D2" :percent="progress">
					<text style="color: #656565;">出货中{{progress}}%</text></arprogress>
			</view>
		</uni-popup>
		<weChatSubTask v-if="qcPlay&&qcPlay.isShow&&!qcPlay.dataValid" ref='task' :showErrTip='false' :checkHasTask='false' runTaskDirectly @get-task="getTaskStatus" />
	</view>
</template>

<script>
	import arprogress from '@/components/ar-circle-progress/index.vue'
	import permision from "@/js_sdk/wa-permission/permission.js" //引入权限判断，主要解决部分机型扫码出现问题
	import weChatSubTask from '@/components/task/weChatSubTask.vue'
	import {mapState} from 'vuex';
	export default {
		components: {
			arprogress,
			weChatSubTask
		},
		data() {
			return {
				content: "",
				bagProduct: "",
				userInfo: "",
				progress: 0,
				submitState:false,
				qcPlay:""
			};
		},
		onShow() {
			this.$util.accessPage(2)
			this.userInfo = this.$api.prePage().userInfo
			this.getDictItemByName()
			console.log("当前页面栈",getCurrentPages().length)
			getApp().globalData.index = 2
			if(uni.getStorageSync("qcPlay")){
				this.qcPlay = uni.getStorageSync("qcPlay")
			}
		},
		onBackPress() {
			// if(this.progress >=10&&this.progress<=95){
			// 	 uni.showModal({
			// 		title: '提示',
			// 		content: '环保袋正在出货中,确定返回上一页？',
			// 		success: res=> {
			// 			if (res.confirm) {
			// 				// 退出当前应用，改方法只在App中生效  
			// 				this.$refs.progress.close()
			// 				this.progress=0
			// 				uni.closeSocket();
			// 				uni.navigateBack({})
			// 			} else if (res.cancel) {
							
			// 			}
			// 		}
			// 	});
			// 	return true
			// }else if (this.progress==0){
			// 	return false
			// }
		},
		computed: {
			...mapState(['codeResults']),
		},
		watch: {
			codeResults(res) {
				if(getApp().globalData.index==2){
					this.scanResult(res.result);
				}
			}
		},
		methods: {
			tapChange() {
				if(this.qcPlay&&this.qcPlay.isShow&&!this.qcPlay.dataValid){
					this.$refs.task.getActivityStatus();
				}else {
					this.scan()
				}
			},
			getTaskStatus(hasTask) {
				if (!hasTask) {
					this.scan();
				}
			},
			//生成订单
			addOrder() {
				if(!this.equipment.stock){
					this.$util.showInfoToast("库存不足，无法兑换")
					return
				}
				let uid= uni.getStorageSync(this.$util.UUID);
				this.$util.doGet(
					`/mallOrder/addOrder/${this.equipment.imei}?imei=${uid}`, {}, {},
					true).then(res => {
					console.log("生成订单", res.data)
					if (res.data.code == this.$ResponseStatus.OK) {
						this.order = res.data.data
						if (this.order.id) {
							this.$refs.alertDialog.open()
						} else {
							this.$util.showInfoToast("兑换失败")
						}
					}

				}).catch(error => {
					console.log(error)
				})
			},
			checkSystemLocationStatus() {
				if (permision.checkSystemEnableLocation()) {
					if (uni.getSystemInfoSync().platform == 'ios') {
						permision.judgeIosPermission("location").then(res => {
							console.log("位置权限状态", res)
							if (res===1) {
								this.scan()
							}else {
								permision.gotoAppPermissionSetting();
							}
						}).catch(error => {
							console.log(error)
						})
					}
					if(uni.getSystemInfoSync().platform == 'android'){
						permision.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION').then(res => {
							console.log("位置权限状态", res)
							if (res===1) {
								this.scan()
							}else {
								permision.gotoAppPermissionSetting();
							}
						}).catch(error => {
							console.log(error)
						})
					}
				} else {
					this.getLocationJurisdiction();
				}
				// var result = permision.checkSystemEnableLocation()
				// console.log(result);
			},
			getLocationJurisdiction(){
				if (uni.getSystemInfoSync().platform == 'android') {
					var Intent = plus.android.importClass('android.content.Intent');
					var Settings = plus.android.importClass('android.provider.Settings');
					var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
					var main = plus.android.runtimeMainActivity();
					main.startActivity(intent); // 打开系统设置GPS服务页面
				}
				// ios平台
				if (uni.getSystemInfoSync().platform == 'ios') {
					var UIApplication = plus.ios.import("UIApplication");
					var application2 = UIApplication.sharedApplication();
					var NSURL2 = plus.ios.import("NSURL");
					var setting2 = NSURL2.URLWithString("App-Prefs:root=Privacy&path=LOCATION");
					application2.openURL(setting2);
					plus.ios.deleteObject(setting2);
					plus.ios.deleteObject(NSURL2);
					plus.ios.deleteObject(application2);
				}
			},
			scanCode(){
				uni.scanCode({
					success: res => {
						uni.showLoading({
							title: "开始识别"
						})
						this.scanResult(res.result);
					}
				})
			},
			scan() {
				if (uni.getSystemInfoSync().platform == 'ios') {
					this.scanCode();
				} else {
					permision.requestAndroidPermission('android.permission.CAMERA').then(res => {
						console.log("权限状态", res)
						if (res===1) {
							this.scanCode();
						}
					}).catch(error => {
						console.log(error)
					})
				}
			},
			// 判断设备是否在附近
			distance() {
			  var La1 = (this.equipLatitude * Math.PI) / 180.0
			  var La2 = (this.latitude * Math.PI) / 180.0
			  var La3 = La1 - La2
			  var Lb3 = (this.equipLongitude * Math.PI) / 180.0 - (this.longitude * Math.PI) / 180.0
			  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)))
			  s = s * 6378.137 // 地球半径
			  s = Math.round(s * 10000) / 10000 - 0.5 // 减去0.1km
			  let distanceKm = s
			  s = s * 1000
			  return s
			},
			iosDistance(){
				let PI = 3.14159265358979323;//圆周率
				let R = 6371229;//地球半径
				
				var lng1 = this.longitude;
				var lat1 = this.latitude;
				
				var lng2 = this.equipLongitude;
				var lat2 = this.equipLatitude;
				
				let x,y,distance;
				let lonres = lng1 > lng2?lng1-lng2:lng2-lng1;
				let latres = lat1 > lat2?lat1-lat2:lat2-lat1;
				x = (lonres) * PI * R * Math.cos(((lat1 + lat2) / 2) * PI / 180) / 180;
				y = (lat2 - lat1) * PI * R / 180;
				 distance = Math.hypot(x, y);
				
				return distance
			},
			scanResult(result){
				uni.showLoading({
					title: "开始识别"
				})
				this.$util.doGet(
					`/api/yun-bag/equipment/spread-qr-equipment/analysis/info?qrContent=${result}`, {}, {},
					true).then(res => {
					uni.hideLoading()
					this.equipment = res.data
					if (this.equipment) {
						uni.getLocation({
							type: 'gcj02',
							highAccuracyExpireTime:6000,
							success: (res) => {
								this.latitude = res.latitude
								this.longitude = res.longitude
								this.equipLatitude = this.equipment.lat
								this.equipLongitude = this.equipment.lng
								let distance = this.distance()
								if (uni.getSystemInfoSync().platform == 'ios') {
									distance = this.iosDistance()
								}
								let equipmentDistance = uni.getStorageSync("distance")
								if(distance<=equipmentDistance){
									this.submitState = false
									this.addOrder();
								}else {
									this.$util.showInfoToast("请在云袋机器旁扫码")
								}
								// let distance = this.GetDistance(this.lat,this.lng,this.equipment.lat,this.equipment.lng)
								console.log("设备距离", distance)
							},fail:(err) =>{
								console.log("获取位置失败", err)
							}
						});
					} else {
						this.$util.showInfoToast("没有识别到设备信息")
					}
				}).catch(error => {
					console.log(error)
					uni.hideLoading()
				})
			},
			//开始兑换
			getDictItemByName() {
				this.$util.doGet("/dict/getDictItemByName?dictCode=bagProduct&itemName=price", {}, {}, true).then(res => {
					if (res.data.code == this.$ResponseStatus.OK) {
						this.bagProduct = res.data.data
						this.content = "确定使用" + this.bagProduct.itemValue + "云豆兑换?"
					}
				}).catch(error => {
					console.log(error)
				})
			},
			//确认兑换
			dialogConfirm() {
				if(this.submitState){
					return
				}
				this.submitState = true
				this.$util.doGet(
					`/mallOrder/payOrder/${this.order.id}`, {}, {},
					true).then(res => {
					console.log(res.data)
					if (res.data.code == this.$ResponseStatus.OK) {
						this.$refs.alertDialog.close()
						// this.shipmentSocket(res.data.data);
						getApp().shipmentSocket(res.data.data,this.userInfo,this.bagProduct)
						uni.navigateBack({})
					}
				}).catch(error => {
					console.log(error)
				})
			},
			shipmentSocket(id) {
				uni.connectSocket({
					url: this.$util.SOCKET_URL + `/webSocket/yunBag/${id}`,
				});
				uni.onSocketOpen(res1 => {
					this.$refs.progress.open()
					this.submitState = false
					console.log('开始出货');
					this.progress = 10
					this.timerSocket = setInterval(() => {
						this.progress += 10
						if (this.progress == 90) {
							this.progress += 5
							if (this.progress == 95) {
								clearInterval(this.timerSocket);
								this.timerSocket = null;
							}
						}
					}, 1000)
				});
				uni.onSocketMessage(res2 => {
					console.log(res2.data)
					let data = JSON.parse(res2.data)
					this.progress = 100
					this.$refs.progress.close()
					if (data.code == this.$ResponseStatus.OK) {
						this.userInfo.totalPoints -= this.bagProduct.itemValue
						this.$util.showInfoToast("出货成功")
					} else {
						this.$util.showInfoToast("出货失败")
					}
					clearInterval(this.timerSocket);
					this.timerSocket = null;
					this.progress = 0
					uni.closeSocket();
				});
			},
			setProgressBar(progress) {
				this.$refs.progressBar.drawCircle(progress); //参数为1-100
				this.$refs.progressBar.drawLine();
			},
			dialogClose() {
				this.$util.doGet(
					`/mallOrder/cancelOrder/${this.order.id}`, {}, {},
					true).then(res => {
					if (res.data.code == this.$ResponseStatus.OK) {
						this.$refs.alertDialog.close()
					}
				}).catch(error => {
					console.log(error)
				})
			},
		},
		beforeDestroy() {
			clearInterval(this.timerSocket);
			this.timerSocket = null;
		}
	}
</script>

<style lang="scss">
	.global-button {}
</style>
